// src-tauri/src/content_filter.rs
use fancy_regex::Regex;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum ContentSafety {
    Safe,
    Suspicious,
    Unsafe(String), // 包含原因
}

#[derive(Serialize, Deserialize)]
pub struct ContentFilter {
    bad_patterns: Vec<Regex>,
    allowed_file_types: Vec<String>,
    max_file_size: u64,
}

impl ContentFilter {
    pub fn new() -> Self {
        let mut filter = Self {
            bad_patterns: Vec::new(),
            allowed_file_types: vec![
                "pdf".to_string(),
                "py".to_string(),
                "ipynb".to_string(),
                "txt".to_string(),
                "md".to_string(),
            ],
            max_file_size: 50 * 1024 * 1024, // 50MB
        };
        
        // 添加不良内容模式（简化示例）
        filter.bad_patterns.push(
            Regex::new(r"(?i)(malware|virus|exploit|hack)").unwrap()
        );
        
        filter
    }
    
    pub fn is_safe_filename(&self, filename: &str) -> bool {
        // 检查文件类型
        let extension = filename.split('.').last().unwrap_or("").to_lowercase();
        if !self.allowed_file_types.contains(&extension) {
            return false;
        }
        
        // 检查文件名中是否包含可疑模式
        for pattern in &self.bad_patterns {
            if pattern.is_match(filename).unwrap_or(false) {
                return false;
            }
        }
        
        true
    }
    
    pub fn scan_content(&self, content: &[u8]) -> ContentSafety {
        let content_str = String::from_utf8_lossy(content);
        
        for pattern in &self.bad_patterns {
            if pattern.is_match(&content_str).unwrap_or(false) {
                return ContentSafety::Unsafe(pattern.as_str().to_string());
            }
        }
        
        // 可以集成更复杂的ML模型
        if self.detect_suspicious_patterns(&content_str) {
            return ContentSafety::Suspicious;
        }
        
        ContentSafety::Safe
    }
    
    fn detect_suspicious_patterns(&self, content: &str) -> bool {
        // 简化的可疑模式检测
        content.len() > 10000 && content.contains("executable")
    }
}